﻿/* QImageUtils.h
 * 
 * Copyright (C) 2020, 2021 Yuan LI
 * email:18069211@qq.com
 * https://blog.csdn.net/liyuanbhu
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#ifndef QIMAGEUTILS_H
#define QIMAGEUTILS_H
#include <QImage>

/**
 *  \brief colorReduce  减少图像中的颜色。
 *  
 *  \param [in] image 图像。可以是灰度图像或者彩色图像
 *  \param [in] div 颜色间隔。间隔之内的都认为是同一个颜色。
 *  \return 
 *  
 *  \details
 */
void colorReduce(QImage &image, int div=64);
/**
 * @brief roi 类似于 image.copy() 但是不拷贝图像数据，而是和原始图像共享数据
 * @param image 原始图像
 * @param rect 如果 rect 的区域超出了 image 的区域，将会被裁剪。这一点和 copy() 不同。
 * @return
 */
QImage roi(const QImage &image, const QRect &rect);

/**
 * @brief toGray 将图像转化为灰度图像，暂时只支持几种 Format。 如果原始图像就是灰度，那么直接返回原始图像，不拷贝数据。
 * @param image
 * @return
 */
QImage toGray(const QImage &image);


/**
 * @brief convertToGray 将图像转化为灰度图像, 利用 QImage::convertToFormat 实现。
 * @param image
 * @return
 */
QImage convertToGray(const QImage &image);

/**
 * @brief isGrayImage 判断一幅图像是否为灰度图像
 *          灰度图像包括
 * @return
 */
bool isGrayImage(const QImage &image);

/**
 *  @brief BrightnessMapper 图像亮度、对比度调整。
 *  为了加速计算，用到了查找表。
 */
class BrightnessMapper
{
public:
    BrightnessMapper();
    ~BrightnessMapper();
    void setRedMap(unsigned char red[]); // red 必须有 256 项。
    void setGreenMap(unsigned char green[]); // 必须有 256 项。
    void setBlueMap(unsigned char blue[]);   // 必须有 256 项。
    void setMap(unsigned char map[]); //必须有 256 项，将 RGB 三个查找表设置成相同的。
    void updateBCG(double brightness, double contrast, double gamma);
    void setColorMap(unsigned char red[], unsigned char green[], unsigned char blue[]);
    void apply(const QImage &from, QImage &to);
    QImage apply(const QImage &from);
    unsigned char *redMap(){ return m_red;}
    unsigned char *blueMap(){return m_blue;}
    unsigned char *greenMap(){return m_green;}
    void redMap(double red[256]);
    void greenMap(double green[256]);
    void blueMap(double blue[256]);
private:
    unsigned char m_red[256];
    unsigned char m_green[256];
    unsigned char m_blue[256];
};


#endif // QIMAGEUTILS_H
